﻿#if NET45 || NET46 || NET461 || NET47 || NET472
using System;
using System.Drawing;
using static XTemplate.Utils.Windows.WinAPI;
#endif

namespace XTemplate.Utils.Windows
{
    public static class CaptureWindow
    {
#if NET45 || NET46 || NET461 || NET47 || NET472
        /// <summary>
        /// 根据句柄截图
        /// </summary>
        /// <param name="hWnd">句柄</param>
        /// <returns></returns>
        public static Image ByHwnd(IntPtr hWnd)
        {
            // get te hDC of the target window
            IntPtr hdcSrc = User32.GetWindowDC(hWnd);
            // get the size
            LPRECT windowRect = new LPRECT();
            User32.GetWindowRect(hWnd, ref windowRect);
            int width = windowRect.Right - windowRect.Left;
            int height = windowRect.Bottom - windowRect.Top;
            // create a device context we can copy to
            IntPtr hdcDest = Gdi32.CreateCompatibleDC(hdcSrc);
            // create a bitmap we can copy it to, using GetDeviceCaps to get the width/height
            IntPtr hBitmap = Gdi32.CreateCompatibleBitmap(hdcSrc, width, height);
            // select the bitmap object
            IntPtr hOld = Gdi32.SelectObject(hdcDest, hBitmap);
            // bitblt over
            Gdi32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, (int)WinAPI.CopyPixelOperation.SourceCopy | (int)WinAPI.CopyPixelOperation.CaptureBlt);
            // restore selection
            Gdi32.SelectObject(hdcDest, hOld);
            // clean up
            Gdi32.DeleteDC(hdcDest);
            User32.ReleaseDC(hWnd, hdcSrc);
            // get a .NET image object for it
            Image img = Image.FromHbitmap(hBitmap);
            // free up the Bitmap object
            Gdi32.DeleteObject(hBitmap);
            return img;
        }

        /// <summary>
        /// 根据窗口名称截图
        /// </summary>
        /// <param name="windowName">窗口名称</param>
        /// <returns></returns>
        public static Image ByName(string windowName)
        {
            IntPtr handle = User32.FindWindow(null, windowName);
            IntPtr hdcSrc = User32.GetWindowDC(handle);
            WinAPI.LPRECT windowRect = new WinAPI.LPRECT();
            User32.GetWindowRect(handle, ref windowRect);
            int width = windowRect.Right - windowRect.Left;
            int height = windowRect.Bottom - windowRect.Top;
            IntPtr hdcDest = Gdi32.CreateCompatibleDC(hdcSrc);
            IntPtr hBitmap = Gdi32.CreateCompatibleBitmap(hdcSrc, width, height);
            IntPtr hOld = Gdi32.SelectObject(hdcDest, hBitmap);
            Gdi32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, (int)WinAPI.CopyPixelOperation.SourceCopy);
            Gdi32.SelectObject(hdcDest, hOld);
            Gdi32.DeleteDC(hdcDest);
            User32.ReleaseDC(handle, hdcSrc);
            Image img = Image.FromHbitmap(hBitmap);
            Gdi32.DeleteObject(hBitmap);
            return img;
        }
#endif
    }
}